package com.bum.sock.poll.bo;

import java.util.Arrays;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.math.RandomUtils;

import com.asao.baseware.core.util.MD5;
import com.google.gson.Gson;

public class IdBO {
	Gson	gson;

	public String getId(String callback, String session) {
		String id = genId();
		String json = gson.toJson(Arrays.asList(id, session));
		json = callback + "(" + json + ")";

		return json;
	}

	public static String genId() {
		String id = MD5.instance.md5(RandomUtils.nextDouble() + "*&*^%" + System.currentTimeMillis()).substring(0, 30);
		id = "1" + id + Integer.toHexString(Math.abs(id.hashCode()) % 16);
		return id;
	}

	public static boolean checkId(String id) {
		if (StringUtils.isBlank(id)) {
			return false;
		}
		int version = NumberUtils.toInt(id.substring(0, 1), 0);
		if (version == 1) {
			int len = id.length();
			int hash = Math.abs(id.substring(1, len - 1).hashCode()) % 16;
			int check = Integer.parseInt(id.substring(len - 1, len), 16);
			return hash == check;
		}
		return false;
	}

	public void setGson(Gson gson) {
		this.gson = gson;
	}
}
